package it.fuesi.synotools.services.tasks.filestation;

import android.app.Activity;
import android.content.Context;

import it.fuesi.synotools.R;
import it.fuesi.synotools.activities.FileStationFileDetailActivity;
import it.fuesi.synotools.activities.MainActivity;
import it.fuesi.synotools.fragments.FileStationFragment;
import it.fuesi.synotools.helpers.FormatHelper;
import it.fuesi.synotools.model.base.VoidDataObject;
import it.fuesi.synotools.model.base.VoidResponse;
import it.fuesi.synotools.model.filestation.FileStationClientParameters;
import it.fuesi.synotools.services.cache.CacheService;
import it.fuesi.synotools.services.client.FileStationClient;
import it.fuesi.synotools.services.client.ServiceClientFactory;
import it.fuesi.synotools.services.tasks.base.BaseTask;

/**
 * Created by pascotto on 17/10/14.
 */
public class RenameFile extends BaseTask<VoidResponse, VoidDataObject, FileStationClientParameters> {

    private static final String TAG = RenameFile.class.getName();

    public RenameFile(Context context){
        super(context);
    }


    private FileStationClientParameters params;

    @Override
    protected String getCacheKey() {
        return null;
    }

    @Override
    public VoidResponse run(FileStationClientParameters params)  throws Exception{
            this.params = params;
            publishProgress(getContext().getString(R.string.progress_renaming_file));
            FileStationClient client = ServiceClientFactory.getClient(FileStationClient.class);

            return client.renameFile(FormatHelper.urlEncode(params.getFile_path().replaceAll(",", "\\,")), FormatHelper.urlEncode(params.getName().replaceAll(",", "\\,")));
    }

    @Override
    protected void onPostExecute(VoidResponse voidResponse) {
        super.onPostExecute(voidResponse);

        if(voidResponse != null && voidResponse.isSuccess()){
            CacheService.expireCache(getContext(), FileStationList.CACHE_KEY_PREFIX + params.getFolder_path());
            if(getContext().getClass().equals(FileStationFileDetailActivity.class)){
                FileStationFileDetailActivity main = (FileStationFileDetailActivity) getContext();
                main.setResult(Activity.RESULT_OK);
                main.finish();
            }else{
                MainActivity main = (MainActivity) getContext();
                FileStationFragment frag = (FileStationFragment)main.getCurrentFragment();
                frag.setCurrentFolder(params.getFolder_path() + "/" + params.getName());
                main.onRefresh();
            }
        }
    }
}
